


import tinymce from 'tinymce/tinymce';
import Editor from '@tinymce/tinymce-vue';
import 'tinymce/themes/silver';
import 'tinymce/icons/default/icons'; // 引入图标
import 'tinymce/plugins/image'; // 插入上传图片插件
import 'tinymce/plugins/media'; // 插入视频插件
import 'tinymce/plugins/table'; // 插入表格插件
import 'tinymce/plugins/lists'; // 列表插件
import 'tinymce/plugins/wordcount'; // 字数统计插件
import 'tinymce/plugins/print'; //打印
import 'tinymce/plugins/preview'; // 预览
import 'tinymce/plugins/autolink'; // 自动链接
import 'tinymce/plugins/help'; // 帮助
import 'tinymce/plugins/searchreplace'; // 查找替换
import 'tinymce/plugins/anchor'; // 锚点
import 'tinymce/plugins/insertdatetime'; // 日期
import 'tinymce/plugins/nonbreaking'; // 不间断空格
import 'tinymce/plugins/pagebreak'; // 插入分页符
import 'tinymce/plugins/paste'; // 粘贴符
import 'tinymce/plugins/toc'; // 目录生成器
import 'tinymce/plugins/visualblocks'; // 显示元素范围
import 'tinymce/plugins/codesample'; // 编辑事例
import 'tinymce/plugins/code'; // 编辑源码
import 'tinymce/plugins/directionality'; // 文字方向
import 'tinymce/plugins/fullpage'; // 文档属性
import 'tinymce/plugins/fullscreen'; // 全屏
import 'tinymce/plugins/hr'; // 水平分割线
import 'tinymce/plugins/link'; // 超链接
import 'tinymce/plugins/autoresize'; // 自动高度
import {baseURL,subpath} from '@/util/util';
 export default {
    components: {
		Editor
	},
	props: {
		toolbar: {
			type: [String, Array],
			default:
				'formatselect toc visualblocks fullpage | bold italic forecolor backcolor nonbreaking pagebreak paste searchreplace| alignleft aligncenter alignright alignjustify hr ltr rtl anchor code codesample| bullist numlist outdent indent | insertdatetime lists link image media table | removeformat preview fullscreen print help '
		}
	},
	data() {
		return {
			plugins:
				'lists advlist image media table wordcount preview print autolink help searchreplace advtable anchor insertdatetime nonbreaking pagebreak paste toc visualblocks codesample code directionality fullpage fullscreen hr link',
			initRichText: {
				language_url: subpath+'/tinymce/langs/zh_CN.js',
				language: 'zh_CN',
				skin_url: subpath+'/tinymce/skins/ui/oxide',
				selector: 'textarea',
				plugins:
					'lists advlist image media table wordcount preview print autolink help searchreplace advtable anchor insertdatetime nonbreaking pagebreak paste toc visualblocks codesample code directionality fullpage fullscreen hr link',
				paste_data_images: true,

				toolbar: this.toolbar,
				branding: false,
				menubar: 'file',
				images_upload_handler: (blobInfo, success, failure) => {
					if (blobInfo.blob().size / 1024 / 1024 > 10) {
						failure('上传失败，图片大小请控制在 10M 以内');
					} else {
						if (
							/gif|jpg|jpeg|png|svg|JPEG|GIF|JPG|PNG$/.test(blobInfo.filename().substring(blobInfo.filename().lastIndexOf('.') + 1, blobInfo.filename().length))
						) {
							this.uploadFile(blobInfo, success);
						} else {
							this.$message.error('图片格式为gif，jpg，jpeg，png');
							return;
						}
					}
				}
			},
			editorData: ''
		};
	},
	mounted() {
		tinymce.init({});
	},
	created() {
		
	},
	methods: {
		changeRichValue(value, idertifer) {
      obj['value'] = value
    },
    dataURLtoBlob(baseurl) {
      let arr = baseurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], {
        type: mime
      });
    },
		image2Base64(img) {
			var canvas = document.createElement('canvas');
			canvas.width = img.width;
			canvas.height = img.height;
			var ctx = canvas.getContext('2d');
			ctx.drawImage(img, 0, 0, img.width, img.height);
			let dataURL = canvas.toDataURL('image/jpeg', 0.9);
			if (dataURL.length > 1000000) {
				dataURL = canvas.toDataURL('image/jpeg', 0.1);
			} else if (dataURL.length > 500000) {
				dataURL = canvas.toDataURL('image/jpeg', 0.5);
			}
			return this.dataURLtoBlob(dataURL);
		},

		readImg(file) {
			return new Promise((resolve, reject) => {
				var img = new Image();
				const reader = new FileReader();
				reader.onload = e => {
					img.src = e.target.result;
				};
				reader.readAsDataURL(file);
				img.onload = () => {
					resolve(img);
				};
				img.onerror = e => {
					reject(e);
				};
			});
		},
		async uploadFile(blobInfo, success) {
			const formdata = new FormData();

			const img = await this.readImg(blobInfo.blob());
			const file = this.image2Base64(img);

			formdata.append('file', file);
			formdata.append('TOKEN', sessionStorage.getItem('token'));
			formdata.append('pageId', this.$route.query.uuid);

			const xhr = new XMLHttpRequest();
			xhr.onreadystatechange = () => {
				if (xhr.readyState === 4 && xhr.status === 200) {
					success(JSON.parse(xhr.response).data.url);
				}
			};
			xhr.open('post', baseURL + '/uploadFile', true);
			xhr.send(formdata);
		}
	}
}
